package com.ronsicecream.pos.transaction.opnameitem;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.entities.MasterUnit;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterUnit;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.entities.PosTransactionOpnameItem;
import com.ronsicecream.pos.entities.PosTransactionOpnameItemDetail;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.transaction.opnameitemdetail.OpnameDetail;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * Class Opname is ...
 *
 * Generated on Tue Sep 02 20:40:20 ICT 2014
 *
 * @version 1.0
 * @author Mr. Kazao™
 * @since Bynga 1.0
 *
 */
public class Opname extends Page{
    private Field opnameId;
    private Field opnameUserId;
    private Field opnameUnitId;
    private Field opnameNumber;
    private Field opnameDate;
    private Field opnameKnownBy;
    private Field opnameDescription;
    private Field opnameTimestamp;

    public Opname() {
        super();
        setTheClass(PosTransactionOpnameItem.class);
        setPageDetail(OpnameDetail.class);

        opnameId = new Field();
        opnameId.setName("opnameId");
        opnameId.setCaption("id");
        opnameId.setListProperties("");
        opnameId.setInputProperties("");
        getFields().add(opnameId);

        opnameUserId = new Field();
        opnameUserId.setName("opnameUserId");
        opnameUserId.setCaption("user");
        opnameUserId.setListProperties("");
        opnameUserId.setInputProperties(" ");
        getFields().add(opnameUserId);

        opnameUnitId = new Field();
        opnameUnitId.setName("opnameUnitId");
        opnameUnitId.setCaption("unit");
        opnameUnitId.setListProperties("");
        opnameUnitId.setInputProperties(" ");
        getFields().add(opnameUnitId);

        opnameNumber = new Field();
        opnameNumber.setName("opnameNumber");
        opnameNumber.setCaption("number");
        opnameNumber.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        opnameNumber.setInputProperties(" size=\"30\" readonly");
        opnameNumber.setRequired(true);
        getFields().add(opnameNumber);

        opnameDate = new Field();
        opnameDate.setName("opnameDate");
        opnameDate.setCaption("date");
        opnameDate.setListProperties(" align=\"center\" width=\"8%\" nowrap");
        opnameDate.setInputProperties(" size=\"8\" readonly");
        opnameDate.setDefaultValue(Utility.getTimestamp());
        opnameNumber.setRequired(true);
        getFields().add(opnameDate);

        opnameKnownBy = new Field();
        opnameKnownBy.setName("opnameKnownBy");
        opnameKnownBy.setCaption("Known By");
        opnameKnownBy.setListProperties(" align=\"center\" width=\"12%\" nowrap");
        opnameKnownBy.setInputProperties(" size=\"15\" ");
        opnameKnownBy.setRequired(true);
        opnameKnownBy.setInputCase(Field.CASE_UPPER);
        getFields().add(opnameKnownBy);

        opnameDescription = new Field();
        opnameDescription.setName("opnameDescription");
        opnameDescription.setCaption("description");
        opnameDescription.setListProperties(" width=\"65%\"");
        opnameDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        opnameDescription.setInputType(Field.INPUT_TEXT_AREA);
        opnameDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(opnameDescription);

        opnameTimestamp = new Field();
        opnameTimestamp.setName("opnameTimestamp");
        opnameTimestamp.setCaption("timestamp");
        opnameTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        opnameTimestamp.setInputProperties(" size=\"20\" readonly");
        opnameTimestamp.setDefaultValue(Utility.getTimestamp());
        getFields().add(opnameTimestamp);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);
        
        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(opnameNumber);
        getFieldsAdd().add(opnameDate);
        getFieldsAdd().add(opnameKnownBy);
        getFieldsAdd().add(opnameDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(opnameNumber);
        getFieldsEdit().add(opnameDate);
        getFieldsEdit().add(opnameDescription);

        getFieldsList().clear();
        getFieldsList().add(opnameNumber);
        getFieldsList().add(opnameDate);
        getFieldsList().add(opnameKnownBy);
        getFieldsList().add(opnameDescription);

        getFieldsView().clear();
        getFieldsView().add(opnameNumber);
        getFieldsView().add(opnameDescription);
        getFieldsView().add(opnameKnownBy);
        getFieldsView().add(opnameUserId);
        getFieldsView().add(opnameUnitId);
        getFieldsView().add(opnameTimestamp);

        setController(new OpnameController(this));
        setExportList(getClass().getResourceAsStream("OpnameList.jasper"));
        setExport(getClass().getResourceAsStream("Opname.jasper"));
    }
    
    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        opnameDate.setFormater(DateFormatter.getInstanceDate(this));
        opnameTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
    }

    @Override
    public void beforeAdd() {
        opnameNumber.setDefaultValue(generate());
    }

    class OpnameController extends Controller {

        public OpnameController(Page page) {
            super(page);
            setOrder(opnameTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List detail) {
            PosTransactionOpnameItem opname = (PosTransactionOpnameItem) data;
            opname.setOpnameNumber(generate());
            opname.setOpnameUnitId(getCurrentUnit());
            opname.setOpnameUserId(getCurrentUser());
            opname.setOpnameTimestamp(Utility.getTimestamp());
        }

        @Override
        public void afterInsert(Object data, List list) {
            EntityManager em = getEntityManager();
            try {
                em.getTransaction().begin();
                PosTransactionOpnameItem opname = (PosTransactionOpnameItem) data;
                 String desc = "";
//                 PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
//                        + " WHERE t.unitUnitTypeId.unitTypeId=4 "
//                        + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId()
////                        + " AND t.unitRegionalId.regionalId=" + receipt.getReceiptRegionalId().getRegionalId()
//                         )
//                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
//                opname.setOpnamePosUnitId(posunit);
//                opname.setOpnameRegionalId(posunit.getUnitRegionalId());
                
                for (Object detail : list) {
                    PosTransactionOpnameItemDetail opnameDetail = (PosTransactionOpnameItemDetail) detail;
                    PosMasterItemStock stock = Item.getStockItem(em, opnameDetail.getOpnameDetailItemId(), getCurrentUnit());
                    PosTransactionItemStock itemStock = new PosTransactionItemStock();
                    itemStock.setItemStockId(Sequence.next(itemStock));
                    itemStock.setItemStockItemId(opnameDetail.getOpnameDetailItemId());
                    itemStock.setItemStockUnitId(getCurrentUnit());
                    itemStock.setItemStockUserId(getCurrentUser());
//                    itemStock.setItemStockPosUnitId(posunit);
//                    itemStock.setItemStockRegionalId(posunit.getUnitRegionalId());
//                    itemStock.setItemStockStatusId(opnameDetail.getOpnameDetailStatusId());
                    itemStock.setItemStockType("6");
                    itemStock.setItemStockLast(stock.getItemStockValue());
                    itemStock.setItemStockCurrent(opnameDetail.getOpnameDetailNewValue());
                    itemStock.setItemStockValue(opnameDetail.getOpnameDetailNewValue());
                    itemStock.setItemStockUserId(getCurrentUser());
                    itemStock.setItemStockTimestamp(Utility.getTimestamp());
                    em.persist(itemStock);
                    stock.setItemStockValue(itemStock.getItemStockCurrent());
                    stock.setItemStockTimestamp(Utility.getTimestamp());
                    
                    opnameDetail.setOpnameDetailDescription(desc + "Item " +opnameDetail.getOpnameDetailItemId().toString()+
//                            " dengan Status: "+opnameDetail.getOpnameDetailStatusId().toString() +
                            " Value / Quantity : "+opnameDetail.getOpnameDetailNewValue());
                    
                    
                }
                
                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println("Errorrrr :"+e);
            }
        }
    }
public String generate() {
        HttpSession session = getRequest().getSession();
        String unitCode = ((MasterUnit) session.getAttribute("bynga.unit")).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionOpnameItem opname = (PosTransactionOpnameItem) getEntityManager().createQuery("SELECT t FROM PosTransactionOpnameItem t WHERE t.opnameNumber LIKE '%/" + unitCode + "/opaname/%/" + year + "' ORDER BY t.opnameTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(opname.getOpnameNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/opname/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/opname/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Opname Bahan Baku"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
